package com.by.controller;


import cn.hutool.core.bean.BeanUtil;
import com.by.auth.TokenTemplate;
import com.by.bean.LoginBean;
import com.by.bean.User;
import com.by.common.bean.PageBean;
import com.by.common.bean.ResultBean;
import com.by.common.controller.BaseController;
import com.by.query.UserQuery;
import com.by.service.UserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/v1")
public class UserController extends BaseController {
    @Autowired
    UserService userService;
    @Autowired
    TokenTemplate tokenTemplate;

    @ApiImplicitParam(name = "account", paramType = "query", value = "用户名", dataTypeClass = String.class, required = true)
    @ApiOperation("账号唯一检查")
    @GetMapping("/user/check")
    public ResultBean checkUser(@RequestParam(name = "account", required = true) String account) {
        int rs = userService.queryUserByAccount(account);
        String tmp = rs == 0 ? "账号可用" : "账号不可用";
        return success("账号唯一检查", tmp);
    }


    @ApiOperation("用户列表")
    @PostMapping("/user/query")
    public ResultBean query(@RequestBody UserQuery query) {
        Map params = BeanUtil.beanToMap(query);
        PageBean bean = userService.query(params);
        return success("用户列表", bean);
    }


    @ApiOperation("用户登录")
    @PostMapping("/user/login")
    public ResultBean login(@Validated @RequestBody LoginBean loginBean, BindingResult result) {
        validate(result);
        User user = userService.queryByAccount(loginBean.getAccount());
        if (null == user) {
            return fail("账号不存在");
        }
        //判断密码是否正确
        //因为数据库存入的是md5加密过的数据 所以要对用户输入的密码进行加密 然后在和数据比较
        String pwd = DigestUtils.md5DigestAsHex(loginBean.getPassword().getBytes());
        if (!pwd.equals(user.getPassword())) {
            return fail("密码错误");
        }

        //判断用户的状态
        if (user.getStatus() != 1) {
            return fail("账号被禁用");
        }
        //将User转换为map
        Map map = BeanUtil.beanToMap(user);
        List<String> roleList = new ArrayList<>();
        if (null != user.getIdentification() && !"".equals(user.getIdentification())) {
            roleList.add(user.getIdentification());
        }
        map.put("roles", roleList);
        //移除密码
        map.remove("password");
        //生成token
        String token = tokenTemplate.generateToken(map);
        map.put("accessToken", token);
        return success("登录成功", map);
    }

}
